package com.ygnn.controller;


import com.ygnn.common.Pojo.Users;
import com.ygnn.common.utils.JwtUtil;
import com.ygnn.properties.JwtProperties;
import com.ygnn.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin
@RequiredArgsConstructor
@Api(value = "用户接口", tags = {"用户接口"})
public class UserController {
    @Autowired
    private UserService userService;

    private final JwtProperties jwtProperties;

    /**
     * 用户登录
     *
     * @param code
     * @return
     */
    @Transactional
    @ApiOperation("登录")
    @GetMapping("/login")
    public void login(String code, HttpServletResponse resp) throws IOException {
        //用户登录获取openid
        Users user = userService.login(code);

        if (user != null) {
            HashMap<String, Object> claimsMap = new HashMap<>();
            claimsMap.put("openId", user.getOpenid());
            //创建jwt令牌
            String Newtoken = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claimsMap);
            //将jwt令牌给前端，内容是用户的openid
            String url = jwtProperties.getUrl().concat("/index.html?token=" + Newtoken);
            resp.sendRedirect(url);
        }
    }

}
